/**
 * Created by wanghan on 9/12/2015.
 */

angular.module('chat.controllers', [])
    .controller('MainCtrl', function ($scope, SocketFactory) {
        var vm = $scope;

        vm._app_name = _app_name;
        vm.chats = null;
        vm.uid = null;
        vm.chatDetailMessages = {};
        vm.chatDetailId = null;
        vm.showHistoryMessageLink = false;
        vm.scrollTopOrBottom = 'bottom';
        vm.switchChat = false;
        vm.percentage = 0;

        if (_app_name == "nonghua") {
            vm.isFarmer = (jQuery("#farmer").val() === 'true');
            vm.consultType = jQuery('#consultType') ? jQuery('#consultType').val() : null;
            var CONST_consult = 2;
            var CONST_consultOffset = 0;
            var CONST_complain = 3;
            var CONST_complainOffset = 1;
            var CONST_chatRange = 2;
        } else if (_app_name == "expert") {
            vm.nid = null;
        }

        var CHAT_TYPE_INDIVIDUAL = 0;
        var CHAT_TYPE_ROOM = 1;
        var CHAT_TYPE_MIX = 2;

        // 初始时开始监听chats消息，接收列表及初始消息
        SocketFactory.on('chats', function (data) {
            vm.chats = data.chats;
            console.log(vm.chats);
            vm.uid = data.uid;
            console.log("uid: " + vm.uid);
            vm.groups = data.groups;
            console.log("groups: " + vm.groups);
            if (vm.chatDetailId) {
                // 场景无可能，考虑删除。(如果已经在某个detail画面了，需要重新进入一下)
                var chatKey = vm.chatDetailId;
                vm.chatDetailId = null;
                vm.viewChatDetail(chatKey, vm.chats[chatKey]);
                alert("错误场景！");
            }

            if (_app_name == "nonghua") {
                if (vm.isFarmer) {
                    // 给农户选择默认的客服
                    // 计算农户应该使用的chat_id
                    var farmerChatId = vm.uid * CONST_chatRange + (vm.consultType == 'consult' ? CONST_consultOffset : CONST_complainOffset);
                    vm.retrieveDefaultAgent(vm.chats, farmerChatId);
                }
            }
        });

        // 监听新的会话
        SocketFactory.on('chat', function (data) {
            //vm.chats = data.chats;
            console.log(data);
            for (var chatId in data.chats) {
                //merge chat
                if (chatId in vm.chats) {
                    //merge messages
                    for (var i = 0; i < data.chats[chatId].messages.length; i++) {
                        var j;
                        for (j = 0; j < vm.chats[chatId].messages.length; j++) {
                            if (data.chats[chatId].messages[i].message_id == vm.chats[chatId].messages[j].message_id) {
                                break;
                            }
                        }
                        if (j >= vm.chats[chatId].messages.length) {
                            vm.chats[chatId].messages[j] = data.chats[chatId].messages[i];
                        }
                    }
                } else {
                    vm.chats[chatId] = data.chats[chatId];
                }
            }

            for (var groupName in data.groups) {
                //merge group
                if (groupName in vm.groups) {
                    //merge group chats
                    for (var i = 0; i < data.groups[groupName].length; i++) {
                        var j;
                        for (j = 0; j < vm.groups[groupName].length; j++) {
                            if (data.groups[groupName][i] == vm.groups[groupName][j]) {
                                break;
                            }
                        }
                        if (j >= vm.groups[groupName].length) {
                            vm.groups[groupName][j] = data.groups[groupName][i];
                        }
                    }
                } else {
                    vm.groups[groupName] = data.groups[groupName];
                }
            }
        });

        // 监听新消息
        SocketFactory.on('message', function (data) {
            var message_id = data.message_id;
            var chat_id = data.chat_id;
            var sender_id = data.sender_id;
            var content = data.content;
            var timestamp = data.timestamp;
            console.log(data);

            if (!!vm.chats[chat_id]) {
                vm.chats[chat_id]['messages'].push({
                    'message_id': message_id,
                    'sender_id': sender_id,
                    'content': content,
                    'timestamp': timestamp
                });
				vm.chats[chat_id].timestamp = timestamp;
                if (chat_id == vm.chatDetailId) {
                    // 如果当前画面的chat_id和新消息的id一样，更新checkpoint
                    vm.chats[chat_id].checkpoint = timestamp;
                    SocketFactory.emit('updateCheckpoint', {chat_id: chat_id, user_id: vm.uid}, function (result) {
                        console.log(result);
                        if (result.success) {
                            console.log('updateCheckpoint after reception succeeded');
                        } else {
                            console.log('updateCheckpoint after reception failed');
                        }
                    });
                }
            }
        });

        // 监听错误消息
        SocketFactory.on('errors', function (data) {
            var error_no = data.error_no;
            var message = data.message;
            console.log(data);

            vm.alert('错误[' + error_no + ']: ' + message);

            if (error_no == '10003') {
                window.close();
            }
        });

        SocketFactory.on('ready', function (data) {
            if (_app_name == "nonghua") {
                // 如果是公司内部员工或者经销商，直接发送chats取得好友列表
                if (!vm.isFarmer) {
                    SocketFactory.emit('chats');
                } else if (vm.consultType == 'consult' || vm.consultType == 'complain') {
                    SocketFactory.emit(vm.consultType, null, function (result) {
                        if (result.success) {
                            console.log('succeeded');
                        } else {
                            vm.alert(result.reason);
                            if (result.reason == '所在区未分配客服，请通过其他方式联系我们') {
                                window.close();
                            }
                            console.log('failed');
                        }
                    });
                }
            }
            else {
                SocketFactory.emit('chats');
            }
        });

        SocketFactory.on('disconnect', function() {
            // 收到socket断开连接消息
            vm.alert('连接已断开！');
            window.close();
        });

        vm.getChatViewItem = function (chatValue) {
            // 如果是单聊，找到非自己的用户；如果是聊天组，取系统默认；如果是农户，取组里active用户
            for (var key in chatValue.user) {
                if (!!key && key != vm.uid) {
                    if (chatValue.type == CHAT_TYPE_INDIVIDUAL) {
                        return chatValue.user[key];
                    }
                    if (chatValue.type == CHAT_TYPE_MIX && chatValue.user[key].active == 1) {
                        return chatValue.user[key];
                    }
                }
            }
            return null;
        };

        vm.getChatViewPic = function (chatValue) {
            if (chatValue.type == CHAT_TYPE_ROOM) {
                return chatValue.pic_url;
            } else {
                var item = vm.getChatViewItem(chatValue);
                if (item != null) {
                    return item.pic;
                }
            }
            return null;
        };

        vm.getChatViewName = function (chatId, chatValue) {
            if (_app_name == "expert") {
                var client_uid = parseInt(chatId / 10000);
                return chatValue.user[client_uid].name + ' 咨询 ' + chatValue.title;
            } else {
                if (chatValue.type == CHAT_TYPE_ROOM) {
                    return chatValue.title;
                } else {
                    var item = vm.getChatViewItem(chatValue);
                    if (item != null) {
                        return item.name;
                    }
                }
                return null;
            }
        };

        if (_app_name == "nonghua") {
            vm.retrieveDefaultAgent = function (chats, farmerChatId) {
                var chatKey = null;
                var chatValue = null;
                var count = 0;
                for (var key in chats) {
                    if (key == farmerChatId) {
                        chatKey = key;
                        chatValue = chats[key];
                        count++;
                    }
                }
                if (count != 1) {
                    vm.alert('获取客服列表错误，请刷新。');
                }
                vm.viewChatDetail(chatKey, chatValue);
            }
        }

        vm.viewChatDetail = function (chatKey, chatValue) {
            if (chatKey == vm.chatDetailId) {
                // 同一对象，返回
                return;
            }
            // 初始化不显示上传按钮
            vm.disableUploadButtonOnly(false);
            // 切换对象，告诉messages更换视图
            vm.switchChat = true;
            // 滚动到最后
            vm.scrollTopOrBottom = "bottom";
            // 设置聊天ID
            vm.chatDetailId = chatKey;
            // 设置聊天对象名
            if (_app_name == "expert") {
                vm.clientId = parseInt(chatKey / 10000);
                vm.chatDetailName = chatValue.title;
                vm.nid = chatKey % 10000;
            } else {
                vm.chatDetailName = vm.getChatViewName(chatKey, chatValue);
            }
            // 切换消息聊天对象
            vm.chatDetailUsers = chatValue.user;
            // 切换消息内容
            vm.chatDetailMessages = chatValue.messages;
            // 向下发送更新消息
            vm.$broadcast('clearState', {chat_id: chatKey});
            // 显示历史消息link
            vm.showHistoryMessageLink = true;
            // 更新checkpoint
            vm.chats[chatKey].checkpoint = new Date().getTime();
            var content = {chat_id: chatKey, user_id: vm.uid};
            SocketFactory.emit('updateCheckpoint', content, function (result) {
                console.log(result);
                if (result.success) {
                    console.log('updateCheckpoint succeeded');
                } else {
                    console.log('updateCheckpoint failed');
                }
            });
        };

        vm.viewHistoryMessage = function (chatId, detailMessages) {
            var minMessageId = detailMessages.length > 0 ? detailMessages[0].message_id : 0;

            var info = {
                chat_id: chatId,
                message_id: minMessageId
            };

            SocketFactory.emit('historyMessages', info, function (result) {
                console.log(result);
                if (result.success) {
                    for (var i = 0; i < result.historyMessages.length; i++) {
                        vm.chatDetailMessages.unshift(result.historyMessages[i]);
                    }
                    vm.scrollTopOrBottom = 'top';
                    console.log('succeeded');
                } else {
                    vm.alert(result.reason);
                    console.log('failed');
                }
            });
        };

        vm.sendMessageOrFile = function () {
            if (!vm.chatDetailId) {
                vm.alert('请选择聊天对象');
                return;
            }
            if (!vm.chats[vm.chatDetailId]) {
                vm.alert('该聊天对象已下线');
                return;
            }
            if (!jQuery("#file").val()) {
                var content = vm.replaceSpecials(jQuery('#editArea').val());

                if (content.length > 255 || content.length == 0) {
                    vm.alert('消息必须在100字内且不为空');
                    return;
                }
                // 发送消息
                var message = {
                    'chat_id': vm.chatDetailId,
                    'chat_type': vm.chats[vm.chatDetailId].type,
                    'content': content
                };
                //message.chat_id = vm.chatDetailId;
                //message.content = content;
                SocketFactory.emit('message', message, function (result) {
                    console.log(result);
                    if (result.success) {
                        jQuery('#editArea').val('');
                        vm.chatDetailMessages.push({
                            'message_id': result.message_id,
                            'sender_id': vm.uid,
                            'content': content,
                            'timestamp': result.timestamp
                        });
						vm.chats[vm.chatDetailId].timestamp = result.timestamp;
                        if (!!result.extra_message) {
                            console.log(result.extra_message);
                        }
                        console.log('succeeded');
                        vm.scrollTopOrBottom = 'bottom';
                    } else {
                        vm.alert(result.reason);
                        console.log('failed');
                    }
                });
            } else {
                var file = window.file;

                if (file.size <= 0 || file.size >= 5000000) {
                    vm.alert('文件不能为空或者超过5M');
                    return;
                }

                vm.percentage = 0;
                vm.disableUpload(true);

                SocketFactory.upload('file', file, {
                    chat_id: vm.chatDetailId,
                    uid: vm.uid,
                    name: file.name,
                    size: file.size
                }, function (result) {
                    console.log(result);
                    if (result.success) {
                        jQuery("#file").val('');
                        vm.chatDetailMessages.push({
                            'message_id': result.message_id,
                            'sender_id': vm.uid,
                            'content': result.content,
                            'timestamp': result.timestamp
                        });
						vm.chats[vm.chatDetailId].timestamp = result.timestamp;
						vm.chats[vm.chatDetailId].checkpoint = result.timestamp;
                        vm.scrollTopOrBottom = 'bottom';
                        console.log('succeeded');
                    } else {
                        vm.alert(result.reason);
                        console.log('failed');
                    }
                }, function (percent) {
                    console.log(percent);
                    vm.percentage = percent;
                    $scope.$apply();
                }, function () {
                    console.log('文件传输完毕');
                    vm.percentage = 100;
                    $scope.$apply();
                    vm.disableUpload(false);
                });
            }
        };

        /**
         * Helper functions
         */
        vm.alert = function (msg) {
            //jQuery(".chat-msg").css('display','');
            //jQuery("#alertMsg").html(msg);
            alert(msg);
        };

        vm.replaceSpecials = function (val) {
            var regN = /\n/g;
            return val.replace(regN, "<br>");
        };

        vm.displayDateTime = function (timestamp, short) {
            return displayDateTime(timestamp, short);
        };

        vm.disableUpload = function(trueOrFalse) {
            if (trueOrFalse) {
                jQuery("#fileUploadButton").css("opacity", 0.4);
                jQuery("#file").attr("disabled", true);
                jQuery('#progressbar').show();
                jQuery("#sendButton").css("opacity", 0.4);
                jQuery('#sendButton').attr("disabled", true);
            } else {
                jQuery("#fileUploadButton").css("opacity", 1);
                jQuery("#file").attr("disabled", false);
                jQuery('#progressbar').hide();
                jQuery("#sendButton").css("opacity", 1);
                jQuery('#sendButton').attr("disabled", false);
            }
        };

        vm.disableUploadButtonOnly = function(trueOrFalse) {
            if (trueOrFalse) {
                jQuery("#fileUploadButton").css("opacity", 0.4);
                jQuery("#file").attr("disabled", true);
            } else {
                jQuery("#fileUploadButton").css("opacity", 1);
                jQuery("#file").attr("disabled", false);
            }
        };

        vm.disableUploadButtonOnly(true);
    })

    .filter('groupBy', function () {
        return function (items, chatIds) {
            var result = {};

            for (var i = 0; i < chatIds.length; i++) {
                if (chatIds[i] in items) {
                    result[chatIds[i]] = (items[chatIds[i]]);
                }
            }

            return result;
        }
    })

    .filter('filterDateBy', function () {
        return function (items, dateName) {
            var result = {};
            var currentDate = parseInt((new Date().getTime()) / 86400000);
            switch (dateName) {
                case 'today':
                    for (var chatId in items) {
                        var date = parseInt(items[chatId].timestamp / 86400000);
                        if (date == currentDate) {
                            result[chatId] = items[chatId];
                        }
                    }
                    break;
                case 'yesterday':
                    for (var chatId in items) {
                        var date = parseInt(items[chatId].timestamp / 86400000);
                        if (date == currentDate - 1) {
                            result[chatId] = items[chatId];
                        }
                    }
                    break;
                default:
                    for (var chatId in items) {
                        var date = parseInt(items[chatId].timestamp / 86400000);
                        if (date < currentDate - 1) {
                            result[chatId] = items[chatId];
                        }
                    }
                    break;
            }
            return result;
        }
    })

    .filter('orderObjectBy', function () {
        return function (items, field_1, field_2, reverse) {
            var filtered = [];
            angular.forEach(items, function (item, index, array) {
				item.id = index;
                filtered.push(item);
            });
            filtered.sort(function (a, b) {
                return (a[field_1] > b[field_1] ? 1 : ((a[field_1] == b[field_1] && a[field_2] > b[field_2]) ? 1 : -1));
            });
            if (reverse) {
                filtered.reverse();
            }
            return filtered;
        };
    });